var $ = getApp().globalData.eui;
$.page({
	data: {
		"meta": {
			"sex": 0,
			"name": "",
			"mobile": "",
			"address": "",
			"longitude": 0,
			"latitude": 0,
			"locationname": "",
			"pai": "",
			isdefault: 0
		},
		id: 0,
		"sexchoices": ["男", "女"],
		title: ""
	},
	onLoad: function (options) {

		var me = this;

		var id = $.toInt(options.id);
		me.setData({
			"title": (id ? '编辑' : '添加') + '收货地址',
			"id": id
		});

		if (id) {
			$.api("mall.RecvAddress.Load", {
				id: id
			})
				.then(function (value) {
					value.isdefault = $.toInt(value.isdefault);
					me.setData({
						meta: value
					});

				});
		}

	},
	onclick8: function (e) {

		var me = this;

		var fnChoose = function () {
			$.wx_chooseLocation({})
				.then(function (location) {
					//location.locationname = location.name;
					//delete location.name;
					me.setData({
						"meta.address": location.address,
						"meta.locationname": location.name,
						"meta.latitude": location.latitude,
						"meta.longitude": location.longitude
					});
				});
		};

		$.isAuthed("scope.userLocation")
			.then(function (bAuthed) {
				if (!bAuthed) {
					$.wx_authorize({
						scope: "scope.userLocation"
					})
						.then(function (res) {
							fnChoose();
						});
				} else
					fnChoose();
			});

	},

	onIsDefaultChange: function (e) {
		var me = this;
		me.setData({
			"meta.isdefault": (e.detail.value ? 1 : 0)
		})
	},
	onRemove: function (e) {
		var me = this;
		$.confirmBox("询问", "确定要删除此收货地址？")
			.then(function () {
				$.api("mall.RecvAddress.Remove", {"id": me.data.id})
					.then(function (value) {
						me.notify("UpdateRecvAddress",[me.data.id]);
						$.back();
					})
			})
	},
	onSubmit: function (e) {

		var me = this;
		var id = me.data.id;

		$.api("mall.RecvAddress." + (id ? "Update" : "Add"), me.data.meta)
			.then(function (value) {
				if( id ){
					me.data.meta.id = value;
				}
				me.notify((id ? "Update" : "Add") + "RecvAddress", [me.data.meta]);
			$.back();
		}, function (err) {
			$.errorBox("错误", err.message)
		})

	}
});